/*
 * @Author      : ZhouQiJun
 * @Date        : 2025-08-09 14:05:44
 * @LastEditors : ZhouQiJun
 * @LastEditTime: 2025-08-20 23:27:55
 * @Description : 设置底图
 */
import { getGis } from '@ol/api'
import { isNil, isNull } from 'es-toolkit'

import { type GisKey } from '../../define'
import { type ILayerOptions } from '../../types.d'
import type BaseLayer from 'ol/layer/Base'

import useLayerFactory from './useLayerFactory'

export default function setBaseLayer(layerOptions: ILayerOptions, key: GisKey): Promise<null | BaseLayer> {
  const gis = getGis(key)
  if (isNil(gis?.map)) {
    return Promise.resolve(null)
  }
  const factory = useLayerFactory(gis)
  if (isNull(factory)) Promise.resolve(null)
  const map = gis.map!
  const layer = factory?.create(layerOptions) as BaseLayer
  const older = map
    .getLayers()
    .getArray()
    .find((e) => e.get('basemap') === true)
  if (!isNil(older)) map.removeLayer(older)
  gis.basemap.name = layerOptions.name as string
  // map.getLayers().insertAt(0, layer)
  map.addLayer(layer)
  layer.set('basemap', true, true)
  layer.set('baseLayer', true, true)
  return new Promise((resolve) => {
    // 等待图层渲染
    map.once('rendercomplete', () => {
      resolve(layer)
    })
  })
}
